<!--
 * @Author: Liz.Zheng
 * @Date: 2021-11-24 10:44:45
 * @LastEditTime: 2023-02-13 18:52:12
 * @LastEditors: 郑亚莉 zhengyali@shequ.life
 * @Description: 添加、编辑合同提醒规则
 * @Motto: Write the code. Change the world.
-->

<template>
  <a-drawer
    :title="title"
    :maskClosable="false"
    :visible="visible"
    :destroyOnClose="true"
    :width="600"
    :body-style="{ paddingBottom: '60px' }"
    @close="closeModal"
  >
    <a-form layout="vertical">
      <a-form-item label="条款类型名称" v-bind="validateInfos.name">
        <a-input placeholder="请输入" v-model:value="modelRef.name" />
      </a-form-item>
      <a-form-item
        label="条款权限"
        v-bind="validateInfos.attribute"
        v-if="!attribute"
      >
        <a-radio-group v-model:value="modelRef.attribute">
          <a-radio
            v-for="property of clauseProperty"
            :key="property.key"
            :value="property.key"
          >
            {{ property.name }}
          </a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item
        label="条款内容"
        v-bind="validateInfos.content"
        v-if="!attribute"
      >
        <a-checkbox-group v-model:value="modelRef.content">
          <a-checkbox
            v-for="contentItem of content"
            :value="contentItem.key"
            :key="contentItem.key"
            :disabled="contentItem.key == 'lease_clause' && leaseClauseDisabled"
          >
            {{ contentItem.name }}
          </a-checkbox>
        </a-checkbox-group>
      </a-form-item>
      <a-form-item
        label="保证金类型"
        v-bind="validateInfos.bond_type"
        v-if="showBondClause"
      >
        <a-select
          v-model:value="modelRef.bond_type"
          placeholder="请选择"
          :options="
            bondType.map((item) => ({
              label: item.name,
              value: item.key,
            }))
          "
        >
        </a-select>
      </a-form-item>
      <a-form-item
        label="费用类型"
        v-bind="validateInfos.cost_type"
        v-if="showLeaseClause"
      >
        <!-- <a-select v-model:value="modelRef.cost_type" placeholder="请选择">
          <a-select-option
            v-for="type of costType"
            :key="type.key"
            :value="type.key"
          >
            {{ type.name }}
          </a-select-option>
        </a-select> -->
        <a-cascader
          v-model:value="modelRef.cost_type"
          :options="costTypeList"
          :load-data="getCostTypeSub"
          placeholder="请选择"
        />
      </a-form-item>
    </a-form>
    <div class="drawer-footer">
      <a-button @click.prevent="closeModal" class="mr-10">关闭</a-button>
      <a-button type="primary" @click.prevent="onSubmit" :loading="submiting">
        保存
      </a-button>
    </div>
  </a-drawer>
</template>

<script>
import { defineComponent, ref, computed, watch, reactive, toRaw } from "vue";
import { Form, message } from "ant-design-vue";
import request from "../../../../common/utils/request";

const useForm = Form.useForm;

export default defineComponent({
  name: "clauseTypeAdd",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [String, Number],
      default: 0,
    },
    attribute: {
      type: String,
      default: "",
    },
  },
  setup(props, context) {
    //   标题
    const title = computed(() => {
      return props.id ? "编辑条款类型" : "添加条款类型";
    });

    /**
     * @description:  表单
     */
    const modelRef = reactive({
      name: "",
      attribute: "",
      content: [],
      bond_type: undefined,
      cost_type: undefined,
    });
    const rulesRef = reactive({
      name: [{ required: true, message: "请输入条款类型名称" }],
      attribute: [{ required: true, message: "请选择条款权限" }],
      content: [{ required: true, message: "请选择条款内容" }],
    });

    const showBondClause = ref(false);
    const showLeaseClause = ref(false);
    watch(
      () => modelRef.content,
      (val) => {
        if (val.includes("bond_clause")) {
          showBondClause.value = true;
          rulesRef.bond_type = [
            { required: true, message: "请选择保证金类型" },
          ];
        } else {
          showBondClause.value = false;
          modelRef.bond_type = undefined;
          delete rulesRef.bond_type;
        }
        if (val.includes("lease_clause")) {
          showLeaseClause.value = true;
          rulesRef.cost_type = [{ required: true, message: "请选择费用类型" }];
        } else {
          showLeaseClause.value = false;
          modelRef.cost_type = undefined;
          delete rulesRef.cost_type;
        }
      },
      {
        deep: true,
      }
    );

    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );

    const closeModal = () => {
      context.emit("cancel");
    };

    const submiting = ref(false);
    const onSubmit = () => {
      validate().then(() => {
        submiting.value = true;
        let params = { ...modelRef, clause_type: 3, needMsg: true };
        params.use_bond = params.content.includes("bond_clause") ? 1 : 0;
        params.use_lease = params.content.includes("lease_clause") ? 1 : 0;
        params.use_incr = params.content.includes("incr_clause") ? 1 : 0;
        params.use_discount = params.content.includes("discount_clause")
          ? 1
          : 0;
        delete params.content;
        if (params.cost_type && params.cost_type.length == 2) {
          params.cost_type = params.cost_type[1];
        }
        console.log("........params", params);
        const success = (res) => {
          message.success(res.msg || "保存成功");
          context.emit("success");
        };
        request
          .post("/org", "/contract/addClause", params)
          .then((res) => success(res))
          .finally(() => {
            submiting.value = false;
          });
      });
    };
    const clauseProperty = ref([]);
    const bondType = ref([]);
    const content = ref([]);
    const getClauseConf = () => {
      request.get("/org", "/contract/getClauseConf").then((res) => {
        const { data } = res;
        clauseProperty.value = data.clauseProperty;
        if (data.clauseProperty.length) {
          modelRef.attribute = props.attribute || data.clauseProperty[0].key;
        }
        bondType.value = data.bondType;
        content.value = data.content;
        const index = content.value.findIndex(
          (item) => item.key == "lease_clause"
        );
        if (index > -1) {
          modelRef.content.push("lease_clause");
        }
      });
    };

    const costTypeList = ref([]);
    const getCostTypeList = () => {
      request.get("/org", "/bill/cost/categoryList", {}).then((res) => {
        if (res.list) {
          costTypeList.value = res.list.map((item) => ({
            label: item.name,
            value: item.id,
            isLeaf: false,
          }));
        }
      });
    };

    const getCostTypeSub = (selectedOptions) => {
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true;
      request
        .get("/org", "/bill/costList", {
          page: 1,
          limit: 9999,
          category_id: targetOption.value,
          status: 1,
        })
        .then((res) => {
          if (res.list) {
            targetOption.loading = false;
            targetOption.children = res.list.map((item) => ({
              label: item.name,
              value: item.cost_type,
              isLeaf: true,
            }));
            costTypeList.value = [...costTypeList.value];
          }
        });
    };

    // 初始化
    const init = () => {
      getClauseConf();
      getCostTypeList();
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          init();
        } else {
          resetFields();
        }
      }
    );

    // 条款内容-租期条款 是否禁用选择
    const leaseClauseDisabled = ref(true);
    watch(
      () => modelRef.attribute,
      (val) => {
        const index = modelRef.content.findIndex(
          (item) => item == "lease_clause"
        );
        if (val == "other") {
          leaseClauseDisabled.value = false;
          if (index >= 0) {
            modelRef.content.splice(index, 1);
          }
        } else {
          leaseClauseDisabled.value = true;
          if (index < 0) {
            modelRef.content.push("lease_clause");
          }
        }
      }
    );

    return {
      title,
      clauseProperty,
      bondType,
      modelRef,
      content,
      showBondClause,
      showLeaseClause,
      validateInfos,
      submiting,
      closeModal,
      onSubmit,

      costTypeList,
      getCostTypeSub,
      leaseClauseDisabled,
    };
  },
});
</script>
